import React, {Component, PropTypes} from "react";
import {Surface} from "gl-react-dom";
import ImageEffects from "./ImageEffects";

const vdomForContent = ({ uri, mainType, type }, onLoadSize) =>
  mainType === "video" ?
  <video loop autoPlay onLoad={e => onLoadSize(e.target.videoWidth, e.target.videoHeight)}>
    <source type={type} src={uri} />
  </video> :
  uri ?
  <img key={uri} src={uri} crossOrigin onLoad={e => onLoadSize(e.target.width, e.target.height)} /> :
  uri;

const width = 400;
const height = 300;

export default class Viewport extends Component {

  constructor (props) {
    super(props);
  }

  onLoadSize = (width, height) => {
    const { content, onLoadNewContent } = this.props;
    onLoadNewContent({ ...content, width, height });
  };

  captureFrame = opts =>
    this.refs.surface.captureFrame(opts);

  render () {
    const {
      onLoadSize,
      props: { content, effects }
    } = this;
    let w = width, h = height;
    const ratio = (content.width && content.height) ? content.height/content.width : 1;
    if (content.width && content.height) {
      h = width * ratio;
   }

    return <div style={{ minWidth: width, flex: 1 }}>
      <div>
        <Surface ref="surface" width={w} height={h} autoRedraw={content.mainType === "video"} opaque={false}>
          <ImageEffects width={w} height={h} {...effects}>
            {vdomForContent(content, onLoadSize)}
          </ImageEffects>
        </Surface>
      </div>
    </div>;
  }
}

Viewport.propTypes = {
  content: PropTypes.object.isRequired,
  effects: PropTypes.object.isRequired,
  onLoadNewContent: PropTypes.func.isRequired
};
